package org.mch.comm.db.exphandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * 描述：
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class ExpRSInsertSQLHandler extends ExpRSSQLHandler {
	private static final long serialVersionUID = 1L;
	private boolean isDeleteSQL;
	private String deletefield;

	public ExpRSInsertSQLHandler(int dbmsType, String tableName, boolean isDeleteSQL, String deletefield) {
		super(dbmsType, tableName);
		this.isDeleteSQL = isDeleteSQL;
		this.deletefield = deletefield;
	}

	public String handler(ResultSet rs) throws Exception {
		if (rs == null) {
			return "";
		}

		StringBuffer delete_sb = new StringBuffer("DELETE FROM ");
		delete_sb.append(getTableName());
		delete_sb.append(" WHERE ");
		delete_sb.append(getDeletefield());
		delete_sb.append(" IN(");

		StringBuffer sb = new StringBuffer("");

		ResultSetMetaData rsm = rs.getMetaData();

		int colcount = rsm.getColumnCount();

		int tmpdel = 0;

		while (rs.next()) {

			StringBuffer insert = new StringBuffer("");
			StringBuffer values = new StringBuffer("");

			insert.append("INSERT INTO ");
			insert.append(getTableName());
			insert.append(" (");

			values.append("VALUES (");

			if (this.isDeleteSQL() && tmpdel > 0) {
				delete_sb.append(",");
			}

			for (int i = 1; i <= colcount; i++) {
				int coltype = rsm.getColumnType(i);
				String colname = rsm.getColumnName(i);

				insert.append(colname);
				if (i != colcount) {
					insert.append(",");
				}

				String sqlstr = byColTypeColNameGetSQLStr(coltype, colname, rs);
				values.append(sqlstr);
				if (this.isDeleteSQL() && colname.equalsIgnoreCase(this.getDeletefield())) {
					delete_sb.append(sqlstr);
				}

				if (i != colcount) {
					values.append(",");
				}
			}

			values.append(")");
			insert.append(")");

			sb.append(insert.toString());
			sb.append("\n");
			sb.append(values.toString());

			sb.append(";");

			sb.append("\n");
			sb.append("\n");

			tmpdel++;
		}

		if (isDeleteSQL()) {
			delete_sb.append(");");
			return delete_sb.append("\n\n").append(sb).toString();
		} else {
			return sb.toString();
		}
	}

	public boolean isDeleteSQL() {
		return isDeleteSQL;
	}

	public String getDeletefield() {
		return deletefield;
	}
}